package com.sgb.kjwl.view.ui.activity.material.hall;

import android.os.Parcelable;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;

import java.util.ArrayList;

public class BehaviorFragmentStatePagerAdapter extends FragmentStatePagerAdapter {

    private ArrayList<? extends Fragment> items;
    private String[] channelEntityList;
    private FragmentManager fm;

    /**
     * 通过控制生命周期的方式来实现懒加载
     *
     * @param fm
     * @param items
     * @param channelEntityList
     */

    public BehaviorFragmentStatePagerAdapter(FragmentManager fm, ArrayList<? extends Fragment> items, String[] channelEntityList) {
        super(fm, FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        this.items = items;
        this.fm = fm;
        this.channelEntityList = channelEntityList;
    }

    @Override
    public int getCount() {
        return items == null ? 0 : items.size();
    }

    @Override
    public Fragment getItem(int position) {
        return items.get(position);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if (channelEntityList != null && channelEntityList.length <= position) return "";
        return channelEntityList[position];
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;

    }

    @Override
    public Fragment instantiateItem(ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container,
                position);
        fm.beginTransaction().show(fragment).commit();
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // super.destroyItem(container, position, object);
        Fragment fragment = (Fragment) object;
        fm.beginTransaction().hide(fragment).commit();
    }

    @Override
    public Parcelable saveState() {
        return null;
    }
}
